package models

import (
	"github.com/jinzhu/gorm"
	"zhanyan/pac/util"
)

// Seat 座位
type Seat struct {
	ID          int `json:"id";gorm:"primary_key"`
	X           float64
	Y           float64
	StudentID   int `json:"student_id"`
	ClassroomID int `json:"classroom_id"`
}

// CheckSeat 检查座位是否存在
func CheckSeat(id int) (bool, error) {
	seat := Seat{ID: id}
	err1 := db.Where(seat).First(&seat).Error

	if err1 != nil && err1 != gorm.ErrRecordNotFound {
		return false, err1
	}

	if seat.ID > 0 {
		return true, nil
	}

	return false, nil
}

// CheckStudentSeat 检查学生是否关联了座位
func CheckStudentSeat(StudentId int) (bool, error) {
	student := Student{}
	student.ID = StudentId
	seat := Seat{}
	err := db.Model(&student).Association("Seat").Find(&seat).Error
	if err != nil {
		return false, err
	}

	if seat.ID > 0 {
		return true, nil
	}

	return false, nil
}

// AddClassroomSeat 在教室中添加座位
func AddClassroomSeat(seat *Seat) (id int, err error) {
	classroom := Classroom{ID: seat.ClassroomID}
	err = db.Model(&classroom).Association("Seat").Append(seat).Error
	if err != nil {
		return 0, util.SeatAddError
	}
	return seat.ID, nil
}

// AddStudentSeat 学生关联座位
func AddStudentSeat(seat *Seat) (id int, err error) {
	student := Student{}
	student.ID = seat.StudentID
	err = db.Model(&student).Association("Seat").Append(seat).Error
	if err != nil {
		return 0, util.SeatAddError
	}
	return seat.ID, nil
}

// UpdateStudentSeat 学生更换座位
func UpdateStudentSeat(seat *Seat) error {
	student := Student{}
	student.ID = seat.StudentID
	err := db.Model(&student).Association("Seat").Replace(seat).Error
	if err != nil {
		return util.StudentChangeSeatError
	}
	return nil
}

// QuerySeat 查询Seat
func QuerySeat(id int) (*Seat, error) {
	seat := Seat{ID: id}
	err := db.First(&seat).Error
	if err != nil {
		return nil, util.SeatNotFoundError
	}
	return &seat, nil
}

// QuerySeats 根据ClassroomID查询Seat
func QuerySeats(classroomId int) (*[]Seat, error) {
	classroom := Classroom{ID: classroomId}
	seats := []Seat{}
	err := db.Model(&classroom).Association("Seat").Find(&seats).Error
	if err != nil {
		return nil, util.SeatNotFoundError
	}
	return &seats, nil
}

// DeleteSeatOnStudent 学生删除与座位的关联
func DeleteSeatOnStudent(seat *Seat) error {
	student := Student{}
	student.ID = seat.StudentID
	err := db.Model(&student).Association("Seat").Clear().Error
	if err != nil {
		return util.StudentDeleteSeatError
	}
	return nil
}

// DeleteSeatOnClass 删除教室中所有座位的关联
func DeleteSeatOnClass(seat *Seat) error {
	class := Classroom{}
	class.ID = seat.ClassroomID
	err := db.Model(&class).Association("Seat").Clear().Error
	if err != nil {
		return util.ClassroomDeleteSeatError
	}
	return nil
}

// DeleteSeats 批量删除座位
func DeleteSeats(ids []int) error {
	seats := []Seat{}
	err := db.Delete(&seats, ids).Error
	if err != nil {
		return util.SeatDeletedError
	}
	return nil
}
